<template>
  <button
    :disabled="disabled || isLoading"
    @click="handleClick"
    :class="[
      ns.blockName(),
      ns.modifierName(type),
      ns.isName('round', round),
      ns.isName('disabled', disabled || isLoading), // 加载的同时禁用按钮
      ns.isName('text', text),
      ns.isName('link', link),
      ns.isName('block', block),
      ns.isName('border', border),
      ns.isName('bashed', bashed),
      ns.modifierName('size', provide_size?.size?.value || size),
      ns.isName('circle', circle),
    ]"
  >
    <!-- 加载图标 -->
    <i v-if="isLoading" class="spinner"></i>
    <!-- 前置图标 -->
    <i
      v-if="frontIcon && !isLoading"
      class=""
      :class="[ns.elementName('icon'), frontIcon]"
    ></i>
    <!-- 按钮文字 -->
    <span :class="[ns.elementName('text')]">
      <slot />
    </span>
    <!-- 后置图标 -->
    <i
      v-if="backIcon && !isLoading"
      class=""
      :class="[ns.elementName('icon'), backIcon]"
    ></i>
  </button>
</template>

<script>
export default {
  name: "z-button",
};
</script>

<script setup>
import { defineProps, ref, computed, inject } from "vue";
import { useNamespace } from "@ZUI/hooks";
const ns = useNamespace("button");

const props = defineProps({
  type: {
    type: String,
    default: "primary",
  },
  round: Boolean,
  disabled: Boolean,
  text: Boolean,
  link: Boolean,
  block: Boolean,
  border: Boolean,
  bashed: Boolean,
  size: {
    type: String,
    default: "", // size:small,default,large
  },
  circle: Boolean,
  // 前方图标
  frontIcon: {
    type: String,
    default: "",
  },
  // 后方图标
  backIcon: {
    type: String,
    default: "",
  },
  loading: Boolean,
  beforeChange: {
    type: Function,
    default: undefined,
  },
});

const emit = defineEmits(["click"]);
const provide_size = inject("buttonGroupProvide", undefined);

// 加载效果
const _loading = ref(false);
const isLoading = computed(() => {
  return props.loading || _loading.value;
});
const handleClick = async (e) => {
  // 检查 beforeChange 是否是一个函数
  if (typeof props.beforeChange === "function") {
    _loading.value = true;
    console.log(typeof props.beforeChange);
    await props
      .beforeChange()
      .then((res) => {
        _loading.value = false;
      })
      .catch((err) => {
        _loading.value = false;
      });
  } else {
    // 如果是点击事件
    emit("click", e);
    return;
  }
};
</script>

<style></style>
<style>
.spinner {
  display: inline-block;
  width: 1em; /* 跟随字体大小 */
  height: 1em;
  border: 2px solid currentColor;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
